<script setup lang='ts'>
import { useGetEnterpriseAccountList } from '@fl/api/purchase'
import { SubmitBtn } from '@fl/components'

const emits = defineEmits(['submit'])

const visible = defineModel<boolean>('visible', { required: true })
const loading = defineModel<boolean>('loading', { required: true })
const { data, isLoading } = useGetEnterpriseAccountList()

const form = ref()

const auditorOptions = computed(() => {
    return data.value ?? []
})

const formValues = ref({
    auditorId: '',
    isAudit: '',
})

const auditorName = computed(() => {
    return formValues.value.auditorId ? auditorOptions.value.find((item: any) => item.value === formValues.value.auditorId)?.label : ''
})

const columns = [
    {
        label: '是否需要审批',
        options: [
            {
                label: '否',
                value: 0,
            },
            {
                label: '是',
                value: 1,
            },
        ],
        prop: 'isAudit',
        valueType: 'radio',
    },
    {
        hideInForm: computed(() => !(Number(formValues.value.isAudit) === 1)),
        label: '请选择审批人',
        options: auditorOptions,
        prop: 'auditorId',
        valueType: 'select',
    },
]

const rules = {
    auditorId: [
        {
            message: '请选择审批人',
            required: true,
        },
    ],
    isAudit: [
        {
            message: '请选择是否需要审批',
            required: true,
        },
    ],
}

function cancel() {
    // 重置数据
    visible.value = false
}
function reset() {
    form.value.formInstance.resetFields()
}
async function submit() {
    const valid = await form.value.formInstance.validate()
    if (valid) {
        const val = {
            ...formValues.value,
            auditorName: auditorName.value,
        }
        emits('submit', val)
    }
}

defineExpose({
    cancel,
})
</script>

<template>
    <PlusDialog v-model="visible"
                title="是否审核订单"
                width="800"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="isLoading"
                    :rows="5"
        />

        <PlusForm v-else
                  ref="form"
                  v-model="formValues"
                  :columns="columns"
                  :label-width="150"
                  :rules="rules"
                  :has-footer="false"
        />

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="loading"
                           @click="submit"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
